import time
import threading

class CircularQueue:
    def __init__(self, size):
        """循环队列实现生产者消费者模型"""
        self.queue = [None] * size
        self.head = 0
        self.tail = 0
        self.size = size
        self.lock = threading.Lock()
        self.not_empty = threading.Condition(self.lock)
        self.not_full = threading.Condition(self.lock)

    def is_empty(self):
        return self.head == self.tail

    def is_full(self):
        return (self.tail + 1) % self.size == self.head

    def put(self, item):
        with self.not_full:
            while self.is_full():
                self.not_full.wait()
            self.queue[self.tail] = item
            self.tail = (self.tail + 1) % self.size
            self.not_empty.notify()

    def get(self):
        with self.not_empty:
            while self.is_empty():
                self.not_empty.wait()
            item = self.queue[self.head]
            self.head = (self.head + 1) % self.size
            self.not_full.notify()
            return item

# 生产者函数
def producer(queue, items):
    for item in items:
        queue.put(item)
        print(f"生产：{item}")
        time.sleep(0.5)

# 消费者函数
def consumer(queue, name):
    while True:
        item = queue.get()
        print(f"消费者{name} 消费：{item}")
        time.sleep(1)

# 测试
if __name__ == "__main__":
    cq = CircularQueue(5)
    producer_thread = threading.Thread(target=producer, args=(cq, [1, 2, 3, 4, 5, 6]))
    consumer1_thread = threading.Thread(target=consumer, args=(cq, "A"))
    consumer2_thread = threading.Thread(target=consumer, args=(cq, "B"))

    producer_thread.start()
    consumer1_thread.start()
    consumer2_thread.start()